package network

import (
	"bytes"
	"io/ioutil"
	"log"
	"net"
	"net/http"
	"time"
)

func HttpPut(url string, ct string, dat []byte, timeout time.Duration) ([]byte, error) {
	req, _ := http.NewRequest("PUT", url, bytes.NewReader(dat))
	req.Header.Add("Content-Type", ct)
	req.Header.Add("Date", "Wed, 12 Sep 2018 02:10:09 GMT")
	log.Print(time.Now())
	client := &http.Client{
		Transport: &http.Transport{
			Dial: func(netw, addr string) (net.Conn, error) {
				conn, err := net.DialTimeout(netw, addr, timeout)
				if err != nil {
					log.Print(err.Error())
					return nil, err
				}
				conn.SetDeadline(time.Now().Add(timeout))
				return conn, nil
			},
			ResponseHeaderTimeout: timeout,
		},
	}
	res, e := client.Do(req)
	if nil != e {
		return nil, e
	}
	defer res.Body.Close()
	body, er := ioutil.ReadAll(res.Body)
	return body, er
}

func HttpPost(url string, ct string, headers map[string]string, dat []byte, timeout time.Duration) ([]byte, error) {
	req, _ := http.NewRequest("POST", url, bytes.NewReader(dat))
	req.Header.Add("Content-Type", ct)
	req.Header.Add("Accept", "*/*")
	for k, v := range headers {
		req.Header.Add(k, v)
	}
	transport := &http.Transport{
		Dial: (&net.Dialer{
			Timeout: 10 * time.Second,
		}).Dial,
		MaxIdleConns: 2,
	}

	client := &http.Client{
		Transport: transport,
		Timeout:   timeout,
	}

	resp, err := client.Do(req)
	if err != nil {
		log.Print(err.Error())
		return nil, err
	}

	defer func() {
		e := resp.Body.Close()
		if nil != e {
			log.Print(e.Error())
			return
		}
	}()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		log.Print(err.Error())

		return nil, err
	}
	return body, nil
}

// HttpGet get请求
func HttpGet(url string, timeout time.Duration) ([]byte, error) {
	client := &http.Client{
		Transport: &http.Transport{
			Dial: func(netw, addr string) (net.Conn, error) {
				conn, err := net.DialTimeout(netw, addr, timeout)
				if err != nil {
					log.Print(err.Error())
					return nil, err
				}
				conn.SetDeadline(time.Now().Add(timeout))
				return conn, nil
			},
			ResponseHeaderTimeout: timeout,
		},
	}
	resp, err := client.Get(url)
	if err != nil {
		log.Print(err.Error())
		return nil, err
	}

	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		log.Print(err.Error())

		return nil, err
	}
	return body, nil
}
